<html>
<head>
	<script type="text/javascript" src="library/MochiKit.js"></script>
	<script type="text/javascript" src="library/SimpleTest.js"></script>
	<link rel="stylesheet" type="text/css" href="library/test.css">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form id="form">
	<input type="text" name="text" id="text" value="TEMP">
	<input type="hidden" name="hidden" id="hidden" value="TEMP">
	<select name="select" id="select">
		<option value="1">A</option>
		<option value="2">B</option>
		<option value="3">C</option>
	</select>
	<input type="checkbox" name="checkbox" id="checkbox" value="on"/>
</form>
<pre id="test">
</pre>
<script type="text/javascript" src="../library/00_MochiKit.js"></script>
<script type="text/javascript" src="../library/00_Components.js"></script>
<script type="text/javascript" src="../library/01_utility.js"></script>
<script type="text/javascript">
try {
	// chrome://tombloo/content/test/test_utility.html
	
	
	// toRoma
	is('アイウエオ'.toRoma(), 'aiueo');
	is('ファイル'.toRoma(), 'fairu');
	is('チャントシタ、ドゥーム。'.toRoma(), 'channtoshita,dwu-mu.');
	is('"アトデヨム","シャシン"'.toRoma(), '"atodeyomu","shashinn"');
	is('アッチ'.toRoma(), 'acchi');
	is('あっち'.toRoma(), 'acchi');
	is('あとでJavaScriptを読む'.toRoma(), 'atodeJavaScriptwo読mu');
	is('webせいさく'.toRoma(), 'webseisaku');
	
	
	// extract
	is('abcdefg'.extract(/bc(de)/), 'de');
	is('abcdefg'.extract(/(bc(de))/, 2), 'de');
	is('abcdefg'.extract(/bc(de)(fg)/, 2), 'fg');
	
	// autoReload();
	CONNECT_TEST = false;
	
	if(CONNECT_TEST){
		SimpleTest.waitForExplicitFinish();
		
		var ds = [];
		ds.push(sendByChannel('http://www.google.com/').addCallback(function(res){
			is(res.status, 200);
			ok(res.responseText);
		}));
		ds.push(sendByChannel('http://www.google.co.jp/translate_t', {
			queryString : {
				langpair : 'en|ja',
			},
			sendContent : {
				hl : 'ja',
				ie : 'UTF8',
				text : 'apple',
				langpair : 'en|ja',
			},
		}).addCallback(function(res){
			is(res.status, 200);
			ok(res.responseText.match('アップル'), '翻訳されたか');
		}));
		
		gatherResults(ds).addBoth(function(){
			SimpleTest.finish()
		});
	}
	
	is('hello world'.md5(), '5eb63bbbe01eeed093cb22bb8f5acdc3');
	
	
	// Firebug無効時はエラーコンソールに出力
	log('LOG TEST');
	warn('WARN TEST');
	try{
		''.no();
	} catch(e){
		error(e);
	}
	
	// queryString
	is(queryString({a:5}), 'a=5');
	is(queryString({a:5}, true), '?a=5');
	is(queryString('a=5'), 'a=5');
	is(queryString({a:void(0)}), '');
	
	setPref('test_string', 'あいうえお');
	is(getPref('test_string'), 'あいうえお');
	
	ok(isEmpty(clearObject({a:1, b:''})));
	
	// フォーム
	populateForm($('form'), {
		text : 'TEXT',
		hidden : 'hidden',
		select : '2',
		checkbox : 'on',
	});
	is($('text').value, 'TEXT');
	is($('hidden').value, 'hidden');
	is($('select').value, '2');
	is($('checkbox').checked, true);
	
	var f = formContents();
	is(f.text, 'TEXT');
	is(f.hidden, 'hidden');
	is(f.select, '2');
	is(f.checkbox, 'on');
	
	// String
	is(' A '.trim(), 'A');
	is('\n \t A\nB\n \n'.trim(), 'A\nB');
	
	ok(! 'ABC,DEF.[]/"()'.includesFullwidth());
	ok(  '"あいう","あとで読む"'.includesFullwidth());
	
	is('1'.pad(3, '0'), '001');
	is('1234'.pad(3, '0'), '1234');
	
	
	// SimpleEnumerator Iterator
	var dir = getProfileDir();
	ok(dir.exists());
	ok(list(dir.directoryEntries).length > 3);
	
	
	// XML Iterator
	var xml = <a><b/><b/><b/></a>;
	is(list(xml.b).length, 3);
	is(typeof(list(xml.b)[2]), 'xml');
	
	
	// Object Iterator
	ok(arrayEqual(
		list({a:1, b:2}),
		[['a', 1], ['b', 2]]));
	
	
	// Array.prototype.split
	ok(arrayEqual(
		[0,1,2,3,4].split(2), 
		[[0, 1], [2, 3], [4]]));
	
	// deferredForEach
	var flag = false;
	deferredForEach([], function(){
		ok(false);
	}).
	addCallback(function(){
		flag=true;
	});
	ok(flag);
	
	var flag = false;
	deferredForEach([1], function(item, index){
		is(item, 1);
		is(index, 0);
	}).
	addCallback(function(){
		flag=true;
	});
	ok(flag);
	
	var arr = [];
	deferredForEach(range(10), function(item){arr.push(item)}).
	addErrback(function(){
		ok(false, 'ループ終端でStopIterationが発生しないこと');
	});
	is(arr.length, 10);
	is(arr[9], 9);
	
	var result;
	deferredForEach(range(10), function(item, index){
		result = item;
		if(result == 3)
			throw StopIteration;
	});
	is(result, 3, '途中キャンセル');
	
	var result;
	deferredForEach(range(10), function(item, index){
		throw 'ERROR';
	}).
	addErrback(function(e){
		result = e.message;
	});
	is(result, 'ERROR', 'エラー等をキャッチできるか')
	
	// DeferredHash
	var l = new DeferredHash({
		s : succeed('SUCCEED'),
		f : fail('FAIL'),
	}).addCallback(function (res) {
		is(res.s[0], true);
		is(res.s[1], 'SUCCEED');
		
		is(res.f[0], false);
		is(res.f[1].message, 'FAIL');
	});
	
	// 正規表現 / エラーメッセージのフィルタ
	function block  (error, re){ok(error.match(re))};
	function through(error, re){ok(! error.match(re))};
	var re;
	
	re = /F:/;
	block  ('F:TOO' , re);
	block  ('F:AUTH', re);
	
	re = /F:(?!AUTH)/;
	through('F:AUTH', re);
	block  ('F:TOO',  re);
	
	re = /F:(?!AUTH|TOO)/;
	through('F:TOO',  re);
	through('F:AUTH', re);
	block  ('F:You',  re);
	
	re = /(F:(?!AUTH|TOO)|T:)/;
	through('F:TOO',  re);
	block  ('T:Post', re);
	block  ('T:You',  re);
	
	re = '(F:(?!AUTH|TOO)|T:(Post))';
	through('F:TOO',  re);
	block  ('T:Post', re);
	through('T:You',  re);
	
	
	is('<a href="http://"><b>ABC</b></a>'.trimTag(), 'ABC');
	is(joinText(['<a href="http://">ABC</a>', null, 'DEF', window.undefined], ' ', true), 'ABC DEF');
	is(joinText(['1', '2']), '1,2');
	is(joinText(['1'], ' ', true), '1');
	is(joinText([null, null], ' ', true), '');
	
	
	// Repository
	var repo = new Repository();
	ok(isEmpty(repo.copyTo({})));
	
	var repo = new Repository({
		name  : 'ABC',
		check : function(c1, c2){
			return c1 < 5;
		},
	});
	ok(repo.copyTo({}).ABC);
	is(repo.names.join(), 'ABC');
	is(repo.values.length, 1);
	is(repo.size, 1);
	is(repo.ABC.name, 'ABC');
	is(repo.ZZZ, null);
	is(repo.find('ABC').length, 1);
	is(repo.find('ZZZ').length, 0);
	is(repo.check(6).length, 0);
	is(repo.check(4).length, 1);
	
	repo.register([{
		name  : 'ABC',
		check : function(c1, c2){
			return c1 < 3;
		},
	},{
		name  : 'DEF',
		check : function(c1, c2){
			return c1 < 1 || c2 > 6;
		},
	},]);
	is(repo.names.join(), 'ABC,DEF');
	is(repo.check(4).length, 0);
	is(repo.check(4, 7).length, 1);
	is(repo.check(2).length, 1);
	is(repo.check(0).length, 2);
	is(repo.check(0)[0].name, 'ABC', '順序が保たれているか');
	is(repo.find('A|D').length, 2);
	is(repo.find(/A|D/).length, 2);
	
	repo.register({
		name  : 'GHI',
		check : function(c){},
	}, 'DEF');
	is(repo.names.join(), 'ABC,GHI,DEF', '途中に追加できるか');
	
	ok(getDataDir().exists(), 'データディレクトリが存在するか');
	
	var event = document.createEvent('KeyboardEvent');
	event.initKeyEvent('keydown', true, true, null,
		true,  //  ctrl,
		false, //  alt,
		true,  //  shift
		false, //  meta
		65, // keyCode,
		0); // in charCode
	is(keyString(event), 'CTRL + SHIFT + A');
	is(keyString(event), 'CTRL + SHIFT + A', '2回目の呼び出し');
	$('text').addEventListener('keydown', function(e){
		cancel(e);
		log(keyString(e));
	}, true);
	
	// Cookie
	ok(getCookies('www.tumblr.com').length > 2, 'Tumblrのログイン情報が取得できるか(未ログインの場合エラー)');
	ok(getCookieString('del.icio.us', '_user'));
	
	// Password
	ok(getPasswords('http://www.tumblr.com').length);
	
	
	// アスペクト
	function Cat(name){
		this.name = name;
	}
	Cat.prototype.mew = function(you){
		return this.name + ' : ' + you + ' MEW!!';
	}
	var cat = new Cat('TAMA');
	var _mew = Cat.prototype.mew; // オリジナルメソッドを保存
	is(cat.mew('taro'), 'TAMA : taro MEW!!');
	
	addAround(Cat.prototype, 'mew', function(proceed, args, target, methodName){
		return proceed(args);
	});
	is(cat.mew.overwrite, 1);
	is(cat.mew('taro'), 'TAMA : taro MEW!!', 'ノーマルなアスペクト追加');
	
	addAround(Cat.prototype, 'mew', function(proceed, args, target, methodName){
		is(methodName, 'mew');
		args[0] = args[0] + ' san';
		return '[' + proceed(args) + ']';
	});
	is(cat.mew.overwrite, 2);
	is(cat.mew('taro'), '[TAMA : taro san MEW!!]', '多重アスペクト、引数と返り値の変形');
	
	Cat.prototype.mew = _mew;
	ok(cat.mew.overwrite == null, 'アスペクトの除去');
	
	
	// getMessage
	is(getMessage('label.action.tomblooOptions'), 'Tomblooの設定');
	
	
	// connected
	var obj = {};
	connect(obj, 'load', function(){});
	ok(connected(obj, 'load'));
	
	connect(obj, 'load', function(){});
	ok(connected(obj, 'load'));
	
	disconnectAll(obj);
	ok(!connected(obj, 'load'));
	
} catch (err) {
	var s = 'test suite failure!\n';
	var o = {};
	var k = null;
	for (k in err) {
		// ensure unique keys?!
		if (!o[k]) {
			s +=  k + ': ' + err[k] + '\n';
			o[k] = err[k];
		}
	}
	ok ( false, s );
}
</script>

</body>
</html>
